import {useEffect, useState} from "react";
import RequestUtils from "../../../utils/requestUtils";
import RequestApis from "../../../apis/requestApis";
import useMessage from "antd/es/message/useMessage";
import {Button, Pagination, Space, Table, Popover, Typography} from "antd";
import {InfoCircleOutlined, CopyOutlined, CheckOutlined} from "@ant-design/icons";
import OperationLogSearch from "../../../components/console/operationLog/operationLogSearch";
import {useNavigate} from "react-router-dom";

const {Text} = Typography;

/**
 * 操作日志页面
 */
const ConsoleOperationLogPage = () => {

    const navigate = useNavigate();
    const [messageApi, contextHolder] = useMessage();
    const [copyStatus, setCopyStatus] = useState({uri: null, param: null}); // 记录复制状态

    // 分页查询请求参数
    const [paginationReq, setPaginationReq] = useState({
        pageNum: 1,
        pageSize: 10
    })

    // 查询操作日志请求参数
    const [pageOperationLogReq, setPageOperationLogReq] = useState({
        requestDescription: "",
        operatorNickname: ""
    })

    // 分页查询操作日志结果
    const [pageOperationLogResp, setPageOperationLogResp] = useState({
        total: 0,
        pageCount: 1,
        records: []
    })

    /**
     * 分页查询系统操作日志
     */
    const pageQuerySystemOperationLog = () => {
        RequestUtils.post(RequestApis.systemLog.pageOperationLog, {
            ...paginationReq,
            ...pageOperationLogReq
        }).then(res => {
            setPageOperationLogResp(res.data.data)
        }).catch(err => {
            messageApi.error(err.message);
        })
    }

    /**
     * 复制文本到剪贴板
     * @param text 要复制的文本
     * @param type 类型（uri/param）
     * @param id 唯一标识（避免同类型多元素冲突）
     */
    const copyToClipboard = (text, type, id) => {
        if (!text) {
            messageApi.warning("无内容可复制");
            return;
        }
        navigator.clipboard.writeText(text).then(() => {
            setCopyStatus({[type]: id});
            messageApi.success("复制成功");
            // 2秒后恢复复制图标
            setTimeout(() => setCopyStatus(prev => ({...prev, [type]: null})), 2000);
        }).catch(() => {
            messageApi.error("复制失败，请手动复制");
        });
    }

    // 字符串截断处理（从第一个字符开始，超出长度加省略号）
    const truncateFromStart = (text, maxLength = 20) => {
        if (!text) return '';
        const str = String(text);
        return str.length > maxLength ? `${str.substring(0, maxLength)}......` : str;
    }

    // 定义表格字段
    const pageSystemOperationLogFields = [
        {
            title: "序号",
            key: "index",
            width: 80,
            align: 'center',
            render: (text, record, index) => (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    color: '#666',
                    fontWeight: 500
                }}>
                    {(paginationReq.pageNum - 1) * paginationReq.pageSize + index + 1}
                </div>
            ),
            isShow: true
        },
        {
            title: "id",
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            isShow: false
        },
        {
            title: "请求接口描述",
            dataIndex: 'requestDescription',
            key: 'requestDescription',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#1890ff',
                    fontWeight: 500,
                    transition: 'color 0.2s ease'
                }}>
                    {text || '-'}
                </div>
            )
        },
        {
            title: "实际请求地址",
            dataIndex: "uri",
            key: "uri",
            align: 'center',
            isShow: true,
            render: (text, record) => (
                <Popover
                    placement="top"
                    mouseEnterDelay={0.3}
                    overlayStyle={{
                        backgroundColor: '#f0f7ff', // 浅蓝色背景
                        borderRadius: '6px',
                        borderColor: '#e6f7ff',
                        padding: '12px',
                        maxWidth: '500px'
                    }}
                    content={
                        <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
                            <Text style={{wordBreak: 'break-all', fontSize: '13px'}}>
                                {text || '无数据'}
                            </Text>
                            <Button
                                size="small"
                                type="text"
                                icon={copyStatus.uri === record.id ? <CheckOutlined style={{color: '#52c41a'}} /> : <CopyOutlined />}
                                onClick={() => copyToClipboard(text, 'uri', record.id)}
                                style={{
                                    alignSelf: 'flex-end',
                                    color: '#1890ff',
                                    padding: '2px 8px'
                                }}
                            >
                                {copyStatus.uri === record.id ? '已复制' : '复制'}
                            </Button>
                        </div>
                    }
                >
                    <div style={{
                        maxWidth: '220px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        color: '#722ed1',
                        fontWeight: 550,
                        cursor: 'pointer',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'flex-start', // 改为左对齐，确保从开头展示
                        gap: '4px',
                        paddingLeft: '8px' // 增加左侧内边距，避免贴边
                    }}>
                        {truncateFromStart(text, 28)}
                        {text && text.length > 28 && <InfoCircleOutlined style={{fontSize: 12, opacity: 0.7}} />}
                    </div>
                </Popover>
            ),
        },
        {
            title: "请求参数",
            dataIndex: 'param',
            key: 'param',
            align: 'center',
            isShow: true,
            render: (text, record) => (
                <Popover
                    placement="top"
                    mouseEnterDelay={0.2}
                    overlayStyle={{
                        backgroundColor: '#effff5', // 浅绿色背景
                        borderRadius: '6px',
                        borderColor: '#eaffea',
                        padding: '12px',
                        maxWidth: '500px'
                    }}
                    content={
                        <div style={{display: 'flex', flexDirection: 'column', gap: '8px'}}>
                            <Text style={{wordBreak: 'break-all', fontSize: '13px'}}>
                                {text || '无参数'}
                            </Text>
                            <Button
                                size="small"
                                type="text"
                                icon={copyStatus.param === record.id ? <CheckOutlined style={{color: '#00cc66'}} /> : <CopyOutlined />}
                                onClick={() => copyToClipboard(text, 'param', record.id)}
                                style={{
                                    alignSelf: 'flex-end',
                                    color: '#238342',
                                    padding: '2px 8px'
                                }}
                            >
                                {copyStatus.param === record.id ? '已复制' : '复制'}
                            </Button>
                        </div>
                    }
                >
                    <div style={{
                        maxWidth: '220px',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap',
                        color: '#238342',
                        fontWeight: 550,
                        cursor: 'pointer',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'flex-start', // 改为左对齐，确保从开头展示
                        gap: '4px',
                        paddingLeft: '8px' // 增加左侧内边距，避免贴边
                    }}>
                        {truncateFromStart(text, 28)}
                        {text && text.length > 28 && <InfoCircleOutlined style={{fontSize: 12, opacity: 0.7}} />}
                    </div>
                </Popover>
            )
        },
        {
            title: "操作执行开始时间",
            dataIndex: 'startTime',
            key: 'startTime',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#333333',
                    fontWeight: 500,
                    fontSize: '13px'
                }}>
                    {text || '-'}
                </div>
            )
        },
        {
            title: '操作耗时',
            dataIndex: 'consumeTime',
            key: 'consumeTime',
            align: 'center',
            isShow: true,
            width: 100,
            render: (text) => {
                let color = '#009900';
                if (text > 1000) color = '#ea580c';
                if (text > 3000) color = '#dc2626';

                return (
                    <div style={{
                        color,
                        fontWeight: 'bolder',
                        transition: 'color 0.2s ease',
                        fontSize: '13px',
                    }}>
                        {text || 0}
                        <span style={{color: 'black'}}>ms</span>
                    </div>
                )
            }
        },
        {
            title: '操作人',
            dataIndex: 'operatorNickname',
            key: 'operatorNickname',
            align: 'center',
            isShow: true,
            render: (text) => (
                <div style={{
                    color: '#6600cc',
                    fontWeight: 550,
                    padding: '2px 4px',
                    borderRadius: '2px',
                    fontSize: '13px'
                }}
                     onMouseOver={(e) => e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.05)'}
                     onMouseOut={(e) => e.currentTarget.style.backgroundColor = 'transparent'}>
                    {text || '未知用户'}
                </div>
            )
        },
        {
            title: '链路追踪id',
            dataIndex: 'traceId',
            key: 'traceId',
            align: 'center',
            isShow: true,
            width: 280,
            render: (text) => (
                <div style={{
                    color: '#374151',
                    fontSize: '13px',
                    fontFamily: 'monospace',
                    wordBreak: 'break-all',
                    maxWidth: '260px',
                    lineHeight: 1.4
                }}>
                    {text || '-'}
                </div>
            )
        },
        {
            title: '操作',
            align: 'center',
            isShow: true,
            render: (text, record) => (
                <Space size="small">
                    <Button
                        size={"small"}
                        type="text"
                        style={{
                            fontSize: '14px',
                            color: '#1890ff',
                            backgroundColor: 'rgba(24, 144, 255, 0.05)',
                            border: '1px solid #91d5ff',
                            borderRadius: '6px',
                            padding: '4px 12px',
                            transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                            display: 'inline-flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                        onMouseEnter={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.1)';
                            e.target.style.transform = 'translateY(-2px)';
                            e.target.style.boxShadow = '0 2px 8px rgba(24, 144, 255, 0.2)';
                        }}
                        onMouseLeave={(e) => {
                            e.target.style.backgroundColor = 'rgba(24, 144, 255, 0.05)';
                            e.target.style.transform = 'translateY(0)';
                            e.target.style.boxShadow = 'none';
                        }}
                        onClick={() => {
                            navigate(`/console/log/trace?traceId=${record.traceId}`)
                        }}
                    >
                        详情
                    </Button>
                </Space>
            )
        }
    ]

    /**
     * 页码变化时查询数据
     */
    useEffect(() => {
        pageQuerySystemOperationLog();
        // eslint-disable-next-line
    }, [paginationReq])

    // 表格行样式 - 交替行背景色
    const getRowClassName = (record, index) => {
        return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
    };

    return (
        <div>
            {contextHolder}

            {/* 查询条件 */}
            <div style={{
                padding: '16px',
                backgroundColor: '#fff',
                borderRadius: '8px',
                marginBottom: '16px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',
            }}>
                <OperationLogSearch
                    setPaginationReq={setPaginationReq}
                    pageOperationLogReq={pageOperationLogReq}
                    setPageOperationLogReq={setPageOperationLogReq}
                    pageQuerySystemOperationLog={pageQuerySystemOperationLog}
                />
            </div>

            {/* 表格展示 */}
            <div style={{
                backgroundColor: '#fff',
                borderRadius: '8px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.04)',
                overflow: 'hidden',
                transition: 'box-shadow 0.3s ease'
            }} onMouseOver={(e) => {
                e.currentTarget.style.boxShadow = '0 4px 16px rgba(0, 0, 0, 0.08)';
            }} onMouseOut={(e) => {
                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.04)';
            }}>
                <Table
                    dataSource={pageOperationLogResp.records}
                    columns={pageSystemOperationLogFields.filter(item => item.isShow)}
                    pagination={false}
                    scroll={{
                        y: 'calc(100vh - 440px)',
                        x: '1200px'
                    }}
                    bordered={false}
                    rowHoverable
                    style={{width: '100%'}}
                    tableLayout="fixed"
                    rowClassName={getRowClassName}
                    headerStyle={{
                        backgroundColor: '#fafafa',
                        color: '#1f2329',
                        fontWeight: 600,
                        fontSize: '14px',
                        borderBottom: '1px solid #e5e6eb',
                        padding: '12px 16px',
                        position: 'sticky',
                        top: 0,
                        zIndex: 1
                    }}
                    bodyStyle={{
                        fontSize: '13px'
                    }}
                    rowStyle={{
                        height: 'auto',
                        minHeight: '60px',
                        transition: 'background-color 0.2s ease'
                    }}
                    loading={{
                        spinning: false,
                        indicator: <div style={{padding: '40px 0'}}>加载中...</div>
                    }}
                    onRow={(record, index) => ({
                        onMouseEnter: (e) => {
                            e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.02)';
                        },
                        onMouseLeave: (e) => {
                            const isEven = index % 2 === 0;
                            e.currentTarget.style.backgroundColor = isEven ? '#fcfcfc' : '#fff';
                        },
                    })}
                />
            </div>

            {/* 分页组件 */}
            <div style={{
                display: "flex",
                justifyContent: "flex-end",
                alignItems: "center",
                height: '60px',
                marginTop: '16px',
                fontSize: '13px'
            }}>
                <Pagination
                    total={pageOperationLogResp.total}
                    current={paginationReq.pageNum}
                    pageSize={paginationReq.pageSize}
                    showSizeChanger
                    showQuickJumper
                    showTotal={(total) => (
                        <div style={{fontSize: '15px'}}>
                            <span>共</span>
                            <span style={{color: 'red', fontWeight: 'bold'}}> {total} </span>
                            <span>条数据</span>
                        </div>
                    )}
                    pageSizeOptions={['10', '20', '50', '100', '200']}
                    onChange={(pageNum, pageSize) => {
                        setPaginationReq({...paginationReq, pageNum, pageSize})
                    }}
                    onShowSizeChange={(current, size) => {
                        setPaginationReq({...paginationReq, pageNum: current, pageSize: size})
                    }}
                    style={{padding: '8px 16px'}}
                    itemStyle={{
                        borderRadius: '4px',
                        margin: '0 2px',
                        transition: 'all 0.2s ease'
                    }}
                    prevIcon={<span style={{transition: 'transform 0.2s ease'}}>←</span>}
                    nextIcon={<span style={{transition: 'transform 0.2s ease'}}>→</span>}
                />
            </div>
        </div>
    )
}

export default ConsoleOperationLogPage;